from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from django_apscheduler.jobstores import DjangoJobStore
from pytz import timezone, utc
from rest_framework import serializers
from .models import Task, Channel
from django.contrib.auth import get_user_model
from datetime import datetime
from django.utils.dateparse import parse_datetime
from rest_framework.response import Response
from django_apscheduler.models import DjangoJob

User = get_user_model()

jobstores = {"default": DjangoJobStore()}
executors = {"default": ThreadPoolExecutor(20), "processpool": ProcessPoolExecutor(5)}
job_defaults = {  # 该参数既可以在创建scheduler对象时使用，也可以用在add_job中，对象范围广、优先级低
    'coalesce': True,  # 是否合并积压的任务。如果设置为 True，当任务运行时间落后时，会只运行一次，而不是运行多次。默认值为 False。
    'max_instances': 2,  # 允许的最大作业实例数。确保同一任务在同一时间不会有多个实例运行。默认值为 1。
    'misfire_grace_time': 30,  # 设置任务错过其执行时间的容忍时间（以秒为单位）。如果任务在这个时间内错过了执行时间，将立即执行。如果设置为 None，则没有时间限制。
    'replace_existing': True  # 如果添加的任务ID已存在，是否替换现有任务。默认值为 False。
}
scheduler = BackgroundScheduler(
    jobstores=jobstores,
    executors=executors,
    job_defaults=job_defaults,
    timezone=timezone('Asia/Shanghai')
)


def clean_task():
    # print("..........................")
    task_id_list = Task.objects.filter(status="in_progress").values('task_id')
    print(task_id_list)
    for task_id_info in task_id_list:
        print(DjangoJob.objects.filter(id=task_id_info.get("task_id")).values("next_run_time"))
        select_result_list = DjangoJob.objects.filter(id=task_id_info.get("task_id")).values("next_run_time")
        # print("next_runt_time:%s" % select_result)
        # print(list(select_result))
        select_value = ""
        for _ in select_result_list:
            select_value = _.get("next_run_time")
            print(select_value)
        if not select_value:
            print(f"更新 id 任务状态: %s" % task_id_info.get("task_id"))
            result = Task.objects.filter(task_id=task_id_info.get("task_id")).update(status="completed")
            print(result)


def cron_task():
    print('cron-taks start----------------')
    job_kwargs = {
        "id": "cron_task_id",
        "func": clean_task,
        "trigger": "cron",
        "hour": "*/1"
    }
    select_cron_task_id = DjangoJob.objects.filter(id="cron_task_id")
    if not select_cron_task_id:
        task_result = scheduler.add_job(**job_kwargs)
        print(task_result)


def start():
    scheduler.start()

